import { defineStore } from 'pinia';
import { ref } from 'vue';
import api from '@/http/api';

export const useDictionaryStore = defineStore('dictionary', () => {
  const dictionaryMap = ref({});
  const loading = ref(false);

  const clearDictionary = () => {
    dictionaryMap.value = {};
  };

  const setDictionaryMap = (dictionaryRes) => {
    dictionaryMap.value = { ...dictionaryRes };
  };

  const getDictionary = async(type) => {
    if (dictionaryMap.value[type] && dictionaryMap.value[type].length) {
      return dictionaryMap.value[type];
    } else {
      return await loadDictionary(type);
    }
  };

  const getDicValue = async(dicCode, dicKey) => {
    let dictionary = await getDictionary(dicCode);
    return ((dictionary || []).find(item => item.key === dicKey) || {})['value'];
  };

  const loadDictionary = async(type) => {
    if (dictionaryMap.value[type] && dictionaryMap.value[type].length) {
      loading.value = false;
      return dictionaryMap.value[type];
    }

    if (loading.value) {
      await sleep(100);
      return await loadDictionary(type);
    }

    loading.value = true;
    if (dictionaryMap.value[type] && dictionaryMap.value[type].length) {
      loading.value = false;
      return dictionaryMap.value[type];
    } else {
      const res = await api.post('/dictionary/queryAllDicData').catch(() => {
        loading.value = false;
      });
      loading.value = false;
      if (res.code === "1") {
        setDictionaryMap(res.data);
        return dictionaryMap.value[type];
      }
    }
  };

  const sleep = async (d) => {
    return new Promise((resolve) => setTimeout(resolve, d));
  };

  return {
    clearDictionary,
    getDictionary,
    getDicValue
  };
});
